package com.bawei.mvvm.http

import androidx.lifecycle.LiveData
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean

//构造
class LiveDataCallAdapter<T>(var responseType:Type): CallAdapter<T,LiveData<T>> {

    override fun responseType(): Type {
      return responseType
    }

    override fun adapt(call: Call<T>): LiveData<T> {
       return object :LiveData<T>(){
           var start = AtomicBoolean(false)
           override fun onActive() {
               super.onActive()
               if(start.compareAndSet(false,true)){
                   call.enqueue(object : Callback<T>{
                       override fun onResponse(call: Call<T>, response: Response<T>) {
                            if(response.code() == 200){//成功
                                postValue(response.body())
                            }else{//失败
                                var apiResponse = ApiResponse(response.code(),response.message(),"")
                                postValue(apiResponse as T)//java中强转
                            }
                       }

                       override fun onFailure(call: Call<T>, t: Throwable) {
                           var apiResponse = ApiResponse(500,t.message,"")
                           postValue(apiResponse as T)//java中强转
                       }

                   })
               }
           }
       }
    }
}